
var wxPassportWrapper = function () {
    var _isAuthorized = function () {
        var scope = 'scope.userInfo';
        return function(cb) {
            if (!wx.getSetting){
                console.log('不支持 wx.getSetting');
                cb(null,true);
                return;
            }
            wx.getSetting({
                success: res => {
                    console.log('wx.getSetting');
                    console.log(res.authSetting);
                    if (res.authSetting[scope]) {
                        cb(null,true);
                    }else{
                        wx.authorize({
                            scope: scope,
                            success: () => {
                                cb(null,true);
                            },
                            fail: (err)=> {
                                console.log(err);
                                cb(new Error(1001,'无法取得授权，可能由于用户取消了授权'),false);
                            }
                        });
                    }
                },
                fail: (err) => {
                    console.log(err);
                    cb(err,false);
                }
            });
        }
    }
    var _openAuthorize = function () {
        return function (cb) {
            var scope = 'scope.userInfo';
            wx.openSetting({
                success: res => {
                    cb(null,res.authSetting[scope]);
                },
                fail: (err) => {
                    console.log(err);
                    cb(err,false);
                }
            });
        }
    }
    var _login = function () {
        return function (cb) {
            wx.login({
                success: res => {
                    cb(null, res.code);
                },
                fail: (err) => {
                    console.log(err);
                    cb(err,false);
                }
            });
        }
    }

    var _getUserInfo = function(){
        var scope = 'scope.userInfo';
        return function (cb) {
            wx.getUserInfo({
                scope: scope,
                withCredentials: true,
                lang: 'zh_CN',
                success: res => {
                    cb(null,res);
                },
                fail: (err) => {
                    console.log(err);
                    cb(err,false);
                }
            });
        }
    }

    var _checkSession = function () {
        return function (cb) {
            wx.checkSession({
                success: res => {
                    cb(null,true);
                },
                fail: ()=> {
                    cb(null,false);
                }
            });
        }
    }

    return {
        isAuthorized: _isAuthorized,
        openAuthorize: _openAuthorize,
        login: _login,
        getUserInfo: _getUserInfo,
        checkSession: _checkSession
    }
}();

module.exports = wxPassportWrapper;
